package mapper

import (
	"goiris/admin/app/web/vo"
	"goiris/common/model"
	"goiris/common/storage"
)

type RoleMapper struct {
}

func (rm *RoleMapper) FindOne(cond *model.CasbinRule) (*model.CasbinRule, error) {
	var (
		err   error
		resut = model.CasbinRule{}
	)
	if err = storage.G_DB.Where(&cond).First(&resut).Error; err != nil {
		return nil, err
	}
	return &resut, nil
}

func (rm *RoleMapper) UpdateOne(role *model.CasbinRule) error {
	return storage.G_DB.Model(&model.CasbinRule{}).Update(&role).Error
}

func (rm *RoleMapper) Delete(ids []int64) error {
	return storage.G_DB.Delete(model.CasbinRule{}, "id in (?)", ids).Error
}

func (rm *RoleMapper) DomainList() (result []string, err error) {
	rows, err := storage.G_DB.Raw("SELECT v2 FROM casbin_rule WHERE p_type='g' GROUP BY v2").Rows()
	defer rows.Close()
	if err != nil {
		return nil, err
	}
	for rows.Next() {
		var a string
		rows.Scan(&a)
		result = append(result, a)
	}
	return
}

func (rm *RoleMapper) Table(vo *vo.RoleVO) ([]*model.CasbinRule, error) {
	var (
		err    error
		result = make([]*model.CasbinRule, 0)
	)
	if vo.Domain == "" || vo.Domain == "all" {
		if err = storage.G_DB.Find(&result, "p_type='p'").Error; err != nil {
			goto ERR
		}
	} else {
		if err = storage.G_DB.Find(&result, "p_type='p' AND v1=?", vo.Domain).Error; err != nil {
			goto ERR
		}
	}
	return result, nil
ERR:
	return nil, err
}
